<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !assetDetailInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="资产移库详情"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('assetMoveDepot:exportDetail') &&
              infoList.data.status !== 1
            "
            @click="exportExcel"
            >导出excel</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button
            v-if="
              $permission('assetMoveDepot:printDetail') &&
              infoList.data.status !== 1
            "
            @click="print"
            >打印</el-button
          > -->
          <!-- //状态: 待提交:1, 待审批:2, 审批中:3, 已驳回:4, 已拒绝：5, 完成：6 -->
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canCheck" @click="check">批准</el-button>
          <el-button v-if="canReject" @click="reject">驳回</el-button>
          <el-button v-if="canRefuse" @click="refuse">拒绝</el-button>
          <el-button v-if="canSalesReview" @click="salesReview">销审</el-button>
          <!-- <el-button v-if="canDoMove" @click="doMove">移库</el-button> -->
          <!-- <el-button v-if="canDoCancel" @click="doCancel">取消</el-button> -->
          <el-button v-if="canRevoke" @click="revoke">撤回</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList" />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
                :isDynamic="true"
              >
                <template v-slot:col-assetName="scope">
                  <span class="slip-edit" @click="showAssetDetail(scope.row)">{{
                    scope.row.assetName
                  }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 修改 -->
    <asset-transfer-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
    />
    <!-- 资产明细 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>

<script setup>
import {
  rejectAssetMoveDepot,
  revokeAssetMoveDepot,
  submitAssetMoveDepott,
  moveAssetMoveDepot,
  checkAssetMoveDepot,
  cancelAssetMoveDepot,
  getAssetMoveDepotById,
  assetMoveDepotDetailCustomizeListAll,
  assetMoveDepotPrintOrder,
  assetMoveDepotExcelOrder,
  refuseAssetMoveDepot,
  cancelAuditAssetMoveDepot,
  batchSubmitAssetMoveDepott,
} from '@/api/asset.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderOpAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import AssetTransferModify from './modify'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'orderId', 'id'])

const infoList = ref({
  data: {},
  fieldList: [
    { label: '单号', value: 'orderNo', type: 'text' },
    { label: '出库仓库', value: 'exportDepotName', type: 'text' },
    { label: '出库部门', value: 'exportDeptName', type: 'text' },
    { label: '入库仓库', value: 'storeDepotName', type: 'text' },
    { label: '入库部门', value: 'storeDeptName', type: 'text' },
    { label: '业务日期', value: 'businessDate', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.orderId,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = ref({
  visible: false,
  orderId: '',
  title: '',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 85,
    orderId: props.id || props.orderId,
    sort: 'operate_time desc',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('assetMoveDepot:printDetail') &&
    infoList.value.data.status !== 1
  )
})
//状态: 待提交:1,待审核:2,待复核:3,待调整:4,完成:5,取消：6,退回：7
//驳回
const canReject = computed(() => {
  return (
    proxy.$permission('assetMoveDepot:reject') &&
    (infoList.value.data.status === 2 || infoList.value.data.status === 3) &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_move_depot_approval_type == 1
  )
})
const canRefuse = computed(() => {
  return (
    proxy.$permission('assetMoveDepot:refuse') &&
    (infoList.value.data.status === 2 || infoList.value.data.status === 3) &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_move_depot_approval_type == 1
  )
})
const canSalesReview = computed(() => {
  return (
    proxy.$permission('assetMoveDepot:salesReview') &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_move_depot_approval_type !== 0 &&
    infoList.value.data.status === 6
  )
})
//移库
const canDoMove = computed(() => {
  return (
    proxy.$permission('assetMoveDepot:move') && infoList.value.data.status === 4
  )
})
//取消
const canDoCancel = computed(() => {
  return (
    proxy.$permission('assetMoveDepot:cancel') &&
    infoList.value.data.status === 4
  )
})
//撤回
const canRevoke = computed(() => {
  return (
    (proxy.$permission('assetMoveDepot:revoke') &&
      infoList.value.data.status === 2) ||
    (infoList.value.data.status === 6 &&
      proxy.$store.state.permission.systemConfig
        .allow_asset_move_depot_approval_type == 0)
  )
})
//审核
const canCheck = computed(() => {
  return (
    proxy.$permission('assetMoveDepot:check') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig
      .allow_asset_move_depot_approval_type == 1
  )
})
//修改
const canSubmit = computed(() => {
  return (
    (proxy.$permission('assetMoveDepot:submit') &&
      infoList.value.data.status === 1) ||
    infoList.value.data.status === 4
  )
})
//修改
const canUpdate = computed(() => {
  return (
    (proxy.$permission('assetMoveDepot:update') &&
      infoList.value.data.status === 1) ||
    infoList.value.data.status === 4
  )
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => modifyInfo.value.visible,
  (value) => {
    if (!value) {
      getMain()
      getList()
    }
  }
)

setData()
function setData() {
  let obj = {}
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
//拒绝
function refuse() {
  proxy
    .$prompt('请输入拒绝理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    .then(({ value }) => {
      const data = {
        orderId: infoList.value.data.id,
        checkOpt: value,
      }
      refuseAssetMoveDepot(data).then((resp) => {
        if (resp) {
          refreshDetail()
        }
      })
    })
}
//销审
function salesReview() {
  cancelAuditAssetMoveDepot(infoList.value.data.id).then((resp) => {
    if (resp) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
    }
  })
}
//驳回
function reject() {
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: '驳回理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: infoList.value.data.id,
        checkOpt: value,
      }
      rejectAssetMoveDepot(data).then((resp) => {
        if (resp) {
          refreshDetail()
        }
      })
    })
}
//退回
function doMove() {
  moveAssetMoveDepot([infoList.value.data.id]).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
//取消
function doCancel() {
  cancelAssetMoveDepot([infoList.value.data.id]).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
//撤回
function revoke() {
  revokeAssetMoveDepot(infoList.value.data.id).then((resp) => {
    if (resp && resp.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
    }
  })
}
//审核
function check() {
  const data = {
    orderId: infoList.value.data.id,
  }
  checkAssetMoveDepot(data).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function update() {
  modifyInfo.value.orderId = infoList.value.data.id
  modifyInfo.value.title = '修改资产移库'
  modifyInfo.value.visible = true
}
//提交
function submit() {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'assetMoveDepot',
    orderIds: [infoList.value.data.id],
  }
  submitAssetMoveDepott(data).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function refreshDetail() {
  getMain()
  getList()
}
function getMain() {
  getAssetMoveDepotById(props.id || props.orderId).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
    }
  })
}
function getList() {
  assetMoveDepotDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}

//导出excel
async function exportExcel() {
  assetMoveDepotExcelOrder(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetMoveDepotDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.id || props.orderId,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id || props.orderId,
      orderType: 64,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id || props.orderId,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'assetAssetMoveDepotDetails-com.slip.spd.entity.vo.asset.assetPoolManage.AssetMoveDepotOrderDetailVO',
    orderIds: [props.id || props.orderId],
  }
  assetMoveDepotPrintOrder(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'assetAssetMoveDepotDetails-com.slip.spd.entity.vo.asset.assetPoolManage.AssetMoveDepotOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
</script>

<style scoped></style>
